home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / manual-p / man_db-2.000 / man_db-2 / man_db-2.3.10 / lib / tempnam.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-07-13  |  2.0 KB  |  108 lines

  1. /*
  2.  * tempnam.c: generate file name for temporary files
  3.  *  
  4.  * Copyright (C), 1994, 1995, Carl Edman
  5.  *
  6.  * You may distribute under the terms of the GNU General Public
  7.  * License as specified in the file COPYING that comes with this
  8.  * distribution.
  9.  *
  10.  */
  11.  
  12. #ifdef HAVE_CONFIG_H
  13. #  include "config.h"
  14. #endif /* HAVE_CONFIG_H */
  15.  
  16. #include <stdio.h>
  17. #include <sys/types.h>
  18. #include <sys/stat.h>
  19. #include <sys/time.h>
  20.  
  21. #if defined(STDC_HEADERS)
  22. #  include <string.h>
  23. #  include <stdlib.h>
  24. #elif defined(HAVE_STRING_H)
  25. #  include <string.h>
  26. #elif defined(HAVE_STRINGS_H)
  27. #  include <strings.h>
  28. #else /* no string(s) header */
  29. extern char *strchr(), *strcat(), *getenv();
  30. #endif /* STDC_HEADERS */
  31.  
  32. #ifdef HAVE_UNISTD_H
  33. #include <unistd.h>
  34. #endif
  35.  
  36. #if HAVE_FCNTL_H
  37. #  include <fcntl.h>
  38. #endif
  39.  
  40. #ifndef NULL
  41. #define NULL 0
  42. #endif
  43.  
  44. #define TEMPNAM_PFX    ""
  45.  
  46. static int isokdir(char *name)
  47.    {
  48.    struct stat buf;
  49.  
  50.    if (name==NULL) return 0;
  51.    if (access(name, R_OK|W_OK|X_OK)==-1) return 0;
  52.    if (stat(name,&buf)==-1) return 0;
  53.    if (buf.st_mode&S_IFDIR==0) return 0;
  54.  
  55.    return 1;
  56.    }
  57.  
  58. /* return filename for temporary file */
  59. char *tempnam (char *dir, char *pfx)
  60.    {
  61.    int n;
  62.    struct timeval tp;
  63.    struct timezone tzp;
  64.    char *ret;
  65.    
  66.    if (!isokdir(dir)) dir=NULL;
  67.    
  68.    if (dir==NULL)
  69.       {
  70.       dir=getenv("TMPDIR");
  71.       if (!isokdir(dir)) dir=NULL;
  72.       }
  73.    
  74. #ifdef P_tmpdir
  75.    if (dir==NULL)
  76.       {
  77.       dir=P_tmpdir;
  78.       if (!isokdir(dir)) dir=NULL;
  79.       }
  80. #endif
  81.    
  82.    if (dir==NULL)
  83.       {
  84.       dir="/tmp";
  85.       if (!isokdir(dir)) dir=NULL;
  86.       }
  87.    
  88.    if (dir==NULL) return NULL;
  89.  
  90.    if (pfx==NULL) pfx=TEMPNAM_PFX;
  91.  
  92.    ret=malloc(strlen(dir)+1+strlen(pfx)+8+1);
  93.    if (ret==NULL) return NULL;
  94.  
  95.    n=getpid();
  96.    sprintf(ret,"%s/%s%08d",dir,pfx,n);
  97.  
  98.    while (access(ret,F_OK)!=-1)
  99.       {
  100.       char number[11];
  101.       gettimeofday(&tp,&tzp);
  102.       sprintf(number,"%d",n^tp.tv_usec^tp.tv_sec);
  103.       sprintf(ret,"%s/%s%08.8s",dir,pfx,number);
  104.       }
  105.  
  106.    return ret;
  107.    }
  108.